// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 查询新收到的申请、线索数量
 */
exports.main = async (event, context) => {
  const { OPENID } = cloud.getWXContext()

  return new Promise((resolve, reject) => {
    let request = null, clue = null, received = null;
    function setResult () {
      if (request !== null && clue !== null && received !== null) {
        resolve({
          total: received.total + request.total + clue.total,
          received: received.total,
          request: request.total,
          clue: clue.total
        })
      }
    }

    db.collection('request')
      .where({ _openid: OPENID, type: 0, tosee: 1 })
      .count()
      .then(res => {
        request = res
        setResult()
      })

    db.collection('request')
      .where({ _openid: OPENID, type: 1, tosee: 1 })
      .count()
      .then(res => {
        clue = res
        setResult()
      })

    db.collection('request')
      .where({ receiver_id: OPENID, status: 0 })
      .count()
      .then(res => {
        received = res
        setResult()
      })
  })
}